package com.jim.jeecg.imvc2.core.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.jim.jeecg.imvc2.core.action.Action;
import com.jim.jeecg.imvc2.core.form.ActionForm;
import com.jim.jeecg.imvc2.core.form.AnnotationBean;
import com.jim.jeecg.imvc2.core.form.FullForm;

/**
 * Servlet implementation class ActionServlet
 */
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);		
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	     
		  String path=this.getPath(request.getServletPath());
		  Map<String,AnnotationBean> mvcMap=(Map<String,AnnotationBean>)this.getServletContext().getAttribute("struts");
		  AnnotationBean annoBean=mvcMap.get(path);
		  String formClass=annoBean.getFormClass();
		  ActionForm actionForm=FullForm.full(formClass, request);
		  String actionType=annoBean.getActionType();
		  Action action=null;
		  String url="";
		  
		  try {
			  Class clazz=Class.forName(actionType);
			  action=(Action)clazz.newInstance();
			  url=action.excute(actionForm, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		  Map<String,String> forwardMap=annoBean.getActionForward();
		  String forward=forwardMap.get(url).trim();
		  RequestDispatcher dispatcher=request.getRequestDispatcher(forward);
		  dispatcher.forward(request, response);  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}
	
	private String getPath(String servletpath)
	{
		
		return StringUtils.stripStart(servletpath, "/").split("\\.")[0];
	}

}
